<?php
declare (strict_types = 1);

namespace app\admin\controller\system;

use app\admin\BaseController;
use app\admin\traits\UploadImage;
use think\Exception;
use think\exception\ValidateException;
use app\common\model\system\Setting as SettingModel;
use app\common\validate\Setting as SettingVaidate;

class Setting extends BaseController
{
    use UploadImage;

    //中间件
    protected $middleware = [
        'method:ajax' => ['only'=>['update','uploadLogo']],
    ];

    /**
     * 上传话题图片**
     */
    public function uploadLogo(){
        return $this->upload(
            SettingModel::UP_FIELD,
            SettingModel::UP_FOLDER
        );
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return view('index',[
            'model' => SettingModel::findOrEmpty(1)
        ]);
    }


    /**
     * 显示编辑资源表单页
     * @return \think\Response
     */
    public function edit()
    {
        return view('edit',[
            'model' => SettingModel::findOrEmpty(1)
        ]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update()
    {
        try{
            //获取数据
            $data = request()->only(['appname','description','keywords','logo','record','email','about']);

            //验证数据
            validate(SettingVaidate::class)->check($data);

            if( !SettingModel::findOrEmpty(1)->save($data) )
                throw new Exception('修改信息失败.');



            return json([
                'code' => 0,
                'msg' => '更新成功.'
            ]);

        }catch (ValidateException $e){
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }catch (\Exception $e){
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }
    }

}
